package com.fadadianqi.logistics.customer.service;

import com.ctc.ctcoss.ws.service.WebServiceSendSms;
import com.fadadianqi.logistics.admin.net.NoSessionConnectedException;
import com.fadadianqi.logistics.customer.model.MsgJob;
import com.fadadianqi.logistics.customer.model.MsgQueue;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 短信群发器
 *
 * @author aroot
 */
@Service
public class MsgSenderService {

    private static final Log log = LogFactory.getLog(MsgSenderService.class);

    private static final ConcurrentHashMap CANCEL_MAP = new ConcurrentHashMap();

    private static final int MAX = 1000;

    @Transactional
    public void cancelByJobId(String jobId) {
        MsgJob job = msgSendJob.getMsgJobById(jobId);
        if (job == null) {
            return;
        }
        job.setStatus(MsgJob.STATUS_CANCEL);
        msgSendJob.updateJob(job);
        msgSendJob.cancelQueueByJobId(jobId);
        CANCEL_MAP.put(jobId, Boolean.TRUE);
    }

    private void doSend(MsgJob job, List<MsgQueue> queueList) throws InterruptedException, NoSessionConnectedException {
        if (job == null) {
            return;
        }
        if (ValidatorHelper.isEmpty(queueList)) {
            return;
        }
        /*if(Boolean.TRUE) {
			System.out.println("************************************************");
		}*/
        String jobId = job.getId();
        String[] _phoneArray = new String[queueList.size()];
        int i = 0;
        String content = null;
        for (MsgQueue queue : queueList) {
            if (CANCEL_MAP.get(jobId) != null) {
                log.info("cancel job id:" + jobId);
                CANCEL_MAP.remove(jobId);
                break;
            }
            _phoneArray[i] = queue.getMobile();
            queue.setStatus(MsgQueue.STATUS_SUCCEED);
            msgSendJob.updateQueue(queue);
            i++;
            if (content == null) {
                content = queue.getContent();
            }
        }
        log.info("SMS phone array: " + _phoneArray.toString());
        log.info("SMS content: " + content);
        WebServiceSendSms.batchSendSMS(_phoneArray, content);
        Thread.sleep(1000);
    }

    /**
     * 首先要连接发送终端例如智能手机
     *
     * @param mobile
     * @param msg
     * @return
     * @throws InterruptedException
     * @throws NoSessionConnectedException
     * @throws Exception
     */
    @Transactional
    public void doSendByJobId(String jobId) throws InterruptedException, NoSessionConnectedException {
        int max = MAX;
        int total = msgSendJob.countQueueByJobIdAndStatus(jobId, MsgQueue.STATUS_ALREADY);
        int pages = total / max;
        if (total % max != 0) {
            pages++;
        }
        MsgJob job = msgSendJob.getMsgJobById(jobId);
        if (job == null) {
            return;
        }
        job.setStatus(MsgJob.STATUS_OK);
        msgSendJob.updateJob(job);
        for (int page = 1; page <= pages; page++) {
            if (CANCEL_MAP.get(jobId) != null) {
                log.info("cancel job id:" + jobId);
                CANCEL_MAP.remove(jobId);
                break;
            }
            Pagination pagination = new Pagination(page, max);
            List<MsgQueue> queueList = msgSendJob.findAllQueue(jobId, MsgQueue.STATUS_ALREADY, pagination);
            doSend(job, queueList);
            int size = queueList.size();
            job.setSucceed(job.getSucceed() + size);
            msgSendJob.updateJob(job);
        }
    }

    @Transactional
    public void continueSendByJobId(String jobId) throws InterruptedException, NoSessionConnectedException {
        int max = MAX;
        int total = msgSendJob.countQueueByJobIdAndStatus(jobId, MsgQueue.STATUS_SENDING);
        int pages = total / max;
        if (total % max != 0) {
            pages++;
        }
        MsgJob job = msgSendJob.getMsgJobById(jobId);
        if (job == null) {
            return;
        }
        job.setStatus(MsgJob.STATUS_OK);
        msgSendJob.updateJob(job);
        for (int page = 1; page <= pages; page++) {
            if (CANCEL_MAP.get(jobId) != null) {
                log.info("cancel job id:" + jobId);
                CANCEL_MAP.remove(jobId);
                break;
            }
            Pagination pagination = new Pagination(page, max);
            List<MsgQueue> queueList = msgSendJob.findAllQueue(jobId, MsgQueue.STATUS_SENDING, pagination);
            doSend(job, queueList);
            int size = queueList.size();
            job.setSucceed(job.getSucceed() + size);
            msgSendJob.updateJob(job);
        }
    }

    @Transactional
    public void anewSendByJobId(String jobId) throws InterruptedException, NoSessionConnectedException {
        int max = MAX;
        int total = msgSendJob.countQueueByJobId(jobId);
        int pages = total / max;
        if (total % max != 0) {
            pages++;
        }
        MsgJob job = msgSendJob.getMsgJobById(jobId);
        if (job == null) {
            return;
        }
        job.setStatus(MsgJob.STATUS_OK);
        msgSendJob.updateJob(job);
        for (int page = 1; page <= pages; page++) {
            if (CANCEL_MAP.get(jobId) != null) {
                log.info("cancel job id:" + jobId);
                CANCEL_MAP.remove(jobId);
                break;
            }
            Pagination pagination = new Pagination(page, max);
            List<MsgQueue> queueList = msgSendJob.findAllQueue(jobId, pagination);
            doSend(job, queueList);
            int size = queueList.size();
            job.setSucceed(job.getSucceed() + size);
            msgSendJob.updateJob(job);
        }
    }

    @Autowired
    private MsgSendJob msgSendJob;
}
